package com.zheng.shop.admin.controller.product;

import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.validator.LengthValidator;
import com.zheng.common.validator.NotNullValidator;
import com.zheng.shop.common.constant.ShopResult;
import com.zheng.shop.common.constant.ShopResultConstant;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.model.*;
import com.zheng.shop.rpc.api.ShopAttributeKeyService;
import com.zheng.shop.rpc.api.ShopAttributeValueService;
import com.zheng.shop.rpc.api.ShopCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/20
 * Time: 16:46
 */
@Controller
@Api(value = "属性管理", description = "属性管理")
@RequestMapping("/manage/product/attribute")
public class AttributeController extends BaseController {
    @Autowired
    private ShopAttributeKeyService keyService;
    @Autowired
    private ShopAttributeValueService valueService;
    @Autowired
    private ShopCategoryService categoryService;

    @ApiOperation(value = "属性首页")
    @RequiresPermissions("product:attribute:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/manage/product/attribute/index.jsp";
    }

    @ApiOperation(value = "属性列表")
    @RequiresPermissions("product:attribute:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, value = "id") Integer productCategoryId) {
        EntityWrapper<ShopAttributeKey> attributeKeyEntityWrapper = new EntityWrapper<>();
        if (null != productCategoryId) {
            attributeKeyEntityWrapper.where("category_id=" + productCategoryId);
        } else {
            return null;
        }
        List<ShopAttributeKey> rows = keyService.selectList(attributeKeyEntityWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", rows.size());
        return result;
    }

    @ApiOperation(value = "新增属性")
    @RequiresPermissions("product:attribute:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model, Integer productCategoryId) {
        model.addAttribute("productCategoryId", productCategoryId);
        return "/manage/product/attribute/create.jsp";
    }

    @ApiOperation(value = "新增属性")
    @RequiresPermissions("product:attribute:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody JSONObject params) {
        Integer productCategoryId = params.getInteger("productCategoryId");
        String key = params.getString("key");
        List<String> values = params.getJSONArray("values").toJavaList(String.class);
        ComplexResult result = doValidator(key, values);
        if(!result.isSuccess()){
            return new ShopResult(ShopResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            keyService.createProductAttribute(productCategoryId, key, values);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }

    private ComplexResult doValidator(String key, List<String> values) {
        ComplexResult result = FluentValidator.checkAll()
                .on(key, new LengthValidator(1, 100, "属性名称"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (result.isSuccess()) {
            for (String value : values) {
                result = FluentValidator.checkAll()
                        .on(value, new LengthValidator(1, 100, "属性值"))
                        .doValidate()
                        .result(ResultCollectors.toComplex());
                if (!result.isSuccess()) {
                    return result;
                }
            }
        }
        return result;
    }

    @ApiOperation(value = "修改属性")
    @RequiresPermissions("product:attribute:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(Model model, @PathVariable("id") Integer id) {
        ShopAttributeKey attributeKey = keyService.selectById(id);
        model.addAttribute("attributeKey", attributeKey);

        EntityWrapper<ShopAttributeValue> attributeValueEntityWrapper = new EntityWrapper<>();
        attributeValueEntityWrapper.where("key_id=" + id);
        List<ShopAttributeValue> valueList = valueService.selectList(attributeValueEntityWrapper);
        model.addAttribute("valueList", valueList);

        return "/manage/product/attribute/update.jsp";
    }

    @ApiOperation(value = "修改属性")
    @RequiresPermissions("product:attribute:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody JSONObject params) {
        Integer keyId = params.getInteger("keyId");
        String key = params.getString("key");
        List<String> values = params.getJSONArray("values").toJavaList(String.class);
        ComplexResult result = doValidator(key, values);
        if(!result.isSuccess()){
            return new ShopResult(ShopResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            keyService.updateProductAttribute(keyId, key, values);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }

    @ApiOperation(value = "删除属性")
    @RequiresPermissions("product:attribute:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@RequestBody List<Integer> ids) {
        try {
            keyService.deleteProductAttribute(ids);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }

    @ApiOperation(value = "复制属性")
    @RequiresPermissions("product:attribute:create")
    @RequestMapping(value = "/copy", method = RequestMethod.GET)
    public String copy(Model model, String keyIds) {
        List<Integer> keyIdList = JSONObject.parseArray(keyIds, Integer.class);
        EntityWrapper<ShopAttributeKey> attributeKeyEntityWrapper = new EntityWrapper<>();
        attributeKeyEntityWrapper.in("id", keyIdList);
        List<ShopAttributeKey> keyList = keyService.selectList(attributeKeyEntityWrapper);

        List<ShopCategory> productCategoryList = categoryService.selectList(null);

        model.addAttribute("productCategoryList", productCategoryList);
        model.addAttribute("keyList", keyList);
        return "/manage/product/attribute/copy.jsp";
    }

    @ApiOperation(value = "复制属性")
    @RequiresPermissions("product:attribute:create")
    @RequestMapping(value = "/copy", method = RequestMethod.POST)
    @ResponseBody
    public Object copy(@RequestBody JSONObject param) {
        Integer productCategoryId = param.getInteger("productCategoryId");
        List<Integer> keyIdList = param.getJSONArray("keyIds").toJavaList(Integer.class);
        if (keyIdList.size() < 1) {
            return new ShopResult(ShopResultConstant.FAILED, "复制失败！没有选择复制的属性！");
        }
        try {
            keyService.copyProductAttribute(keyIdList, productCategoryId);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }

    @ApiOperation(value = "选择图片项")
    @RequiresPermissions("product:attribute:update")
    @RequestMapping(value = "/selectImg", method = RequestMethod.POST)
    @ResponseBody
    public Object selectImg(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        Boolean hasImage = params.getBoolean("hasImage");
        try {
            keyService.selectImage(id, hasImage);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }
}
